# frozen_string_literal: true

class UsersController < ApplicationController
  before_action :set_user, only: %i[show edit update destroy]

  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.where('date = ?', Date.today)
    # debugger
  end

  def show2
    # render html: "hello, world"
    @user = User.find(params[:id])
    @microposts = @user.microposts.where('date = ?', params[:date])
    render "users/show2", :layout => false
    # @microposts = Micropost.joins(:category, :subcategory, :user).select('categories.name,subcategories.name, microposts.task').where('id = ? and date = ?', params[:id], params[:date])

    # @products = Micropost.joins(:category, :subcategory, :user).select('categories.name as cname, subcategories.name as sname, microposts.task as task, microposts.cost as cost, microposts.date as date').where('users.id = ? and date = ?', params[:id], params[:date])
    # render status: 200, json: {
    #   products: @products
    # }.to_json
  end

  def show3
    # render html: "hello, world"
    @user = User.find(params[:id])
    @microposts = @user.microposts.where("cast(strftime('%m', date) as int) = ?" ,Date.today.month)
    render "users/show3", :layout => false
    # @microposts = Micropost.joins(:category, :subcategory, :user).select('categories.name,subcategories.name, microposts.task').where('id = ? and date = ?', params[:id], params[:date])

    # @products = Micropost.joins(:category, :subcategory, :user).select('categories.name as cname, subcategories.name as sname, microposts.task as task, microposts.cost as cost, microposts.date as date').where('users.id = ? and date = ?', params[:id], params[:date])
    # render status: 200, json: {
    #   products: @products
    # }.to_json
  end

  def new
    @user = User.new
  end

  def edit
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)
    if @user.save
      log_in @user
      redirect_to @user
    else
      render :new
    end
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = 'Profile updated'
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    @user.destroy
    redirect_to users_url
  end

  private

  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:number, :name, :password,
                                 :password_confirmation)
  end
end
